<template>
  <div class="personalCenter" v-cloak>
    <div class="personal-side">
      <span>个人中心</span>
    </div>
    <div class="personal-main">
      <div class="personal-main-wrap">
        <el-form :label-position="labelPosition" :model="formData" :rules="rules" :hide-required-asterisk=" way != 'update' " ref="formData" label-width="85px" class="add-user-form" size="small">
          <el-form-item label="姓名:" prop="linkName" v-if="merchantId">
            <p v-if="way == 'look'">{{formData.linkName}}</p>
            <el-input v-if="way == 'update'" class="add-input" type="text" maxlength="30" @keyup.native="replaceName(formData.linkName,formData,'linkName')" v-model="formData.linkName"></el-input>
          </el-form-item>
          <el-form-item label="手机号:">
            <span class="personal-password">{{formData.mobile}}</span>
            <el-button type="text" v-if="way =='look'" @click="phoneVisible = true" size="small">修改手机号</el-button>
          </el-form-item>
          <el-form-item label="头像:" prop="staus">
            <img :src="formData.headUrl || default_head" class="headeImg" v-if="way != 'update'" />
            <el-upload v-else class="avatar-uploader" :show-file-list="false" action="1" :before-upload="beforeUpload" :http-request="uploadFile1">
              <img v-if="formData.headUrl" :src="formData.headUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="登录密码:" style="text-align: left;">
            <span class="personal-password">{{formData.password}}</span>
            <el-button type="text" v-if="way =='look'" @click="dialogVisible = true" size="small">修改密码</el-button>
          </el-form-item>
          <el-form-item label="角色:" prop="list" style="text-align: left;" v-if="merchantId">
            <div class="el-transfer-panel">
              <p class="el-transfer-panel__header">
                <label class="el-checkbox">
                  <span class="el-checkbox__label">角色列表</span>
                </label>
              </p>
              <div class="el-transfer-panel__body">
                <div class="el-transfer-panel__filter el-input el-input--small el-input--prefix">
                  <input type="text" v-model="roleKey" autocomplete="off" placeholder="请输入搜索内容" class="el-input__inner" />
                  <span class="el-input__prefix">
                    <i class="el-input__icon el-icon-search"></i>
                  </span>
                </div>
                <div role="group" aria-label="checkbox-group" class="el-checkbox-group el-transfer-panel__list is-filterable" v-if="formData.list&&formData.list.length>0">
                  <label v-for="(item, index) in formData.list.filter(data => !roleKey || data.roleName.toLowerCase().includes(roleKey.toLowerCase()))" :key="index" role="checkbox" aria-checked="true" class="el-checkbox el-transfer-panel__item is-checked">
                    <span class="el-checkbox__label">
                      <span v-text="item.roleName"></span>
                    </span>
                  </label>
                </div>
                <p class="el-transfer-panel__empty" style="text-align: center!important;" v-else>无数据</p>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="personal-btn">
          <template v-if="way =='look'">
            <el-button type="primary" @click="way = 'update'" v-if="merchantId">修改信息</el-button>
          </template>
          <template v-else>
            <el-button type="primary" v-if="pageState != 0" @click="cancle()" plain>取消</el-button>
            <el-button type="primary" @click="saveForm()">保存信息</el-button>
          </template>
        </div>
      </div>
    </div>
    <!--弹框-->
    <el-dialog title="修改密码" :visible.sync="dialogVisible" width="20%" center :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="modify-passw-box">
        <el-form :label-position="labelPosition" :model="modifyPassw" :rules="rulesBox" ref="modifyPassw" class="add-user-form" size="small">
          <el-form-item>
            <el-input class="add-input" v-model="formData.mobile" placeholder="请输入手机号" prefix-icon="el-icon-printer" disabled></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input class="add-input" v-model="modifyPassw.password" placeholder="请输入旧密码" maxlength="20" prefix-icon="el-icon-edit" onpaste="return false" oncontextmenu="return false" type="password" oncopy="return false" oncut="return false" clearable></el-input>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input class="add-input" v-model="modifyPassw.newPassword" placeholder="请输入新密码" maxlength="20" prefix-icon="el-icon-edit" onpaste="return false" oncontextmenu="return false" type="password" oncopy="return false" oncut="return false" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closePasswBox()" plain>取 消</el-button>
        <el-button type="primary" @click="submitPassw()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改手机号 -->
    <el-dialog title="修改手机号" :visible.sync="phoneVisible" width="30%" :before-close="handleClose">
      <div class="changePhoneBox" v-if="progress == 0">
        <div class="line">
          <div class="title">当前手机号:</div>
          <div class="phone">{{formData.mobile}}</div>
        </div>
        <div class="height"></div>
        <div class="line">
          <div class="title">验证码:</div>
          <el-input class="input" v-model="verification1" @keyup.native="verification1 = util.replaceNumber(verification1)" :maxlength='6' placeholder="请输入验证码"></el-input>
          <el-button class="getCode" type="primary" size="mini" @click="getCode1">{{codeText1}}</el-button>
        </div>
        <p class="tip" v-if="tip1">请输入正确的验证码</p>
      </div>
      <div class="newPhone" v-else>
        <div class="line">
          <div class="title">新手机号:</div>
          <el-input class="input" type="text" v-model="newPhone" @keyup.native="cutOutNumbers()" placeholder="请输入手机号" :maxlength='11'></el-input>
        </div>
        <p class="tip" v-if="tip2">请输入正确的手机号</p>
        <div class="height"></div>
        <div class="line">
          <div class="title">验证码:</div>
          <el-input v-model="verification2" class="input" @keyup.native="verification2 = util.replaceNumber(verification2)" :maxlength='6' placeholder="请输入验证码"></el-input>
          <el-button class="getCode" type="primary" size="mini" @click="getCode2">{{codeText2}}</el-button>
        </div>
        <p class="tip" v-if="tip1">请输入正确的验证码</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancleChange()">取 消</el-button>
        <el-button type="primary" @click="checkMoblieCode" v-if="progress == 0">下 一 步</el-button>
        <el-button type="primary" @click="checkMoblieCode2" v-else>确 认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import md5 from "js-md5";
import default_head from "assets/images/default_head.png";
import util from "@/util";
import { mapState } from "vuex";
import {
  uploadFile,
  findUserInfo,
  updatePersonInfo,
  updatePwd,
  getFile,
  validateCode,
  checkMoblieCode,
  updMobileByCode
} from "@/api";
import Cookies from "js-cookie";
export default {
  data() {
    const checkPassword = (rule, value, callback) => {
      if (util.validChinese(value)) {
        return callback(new Error("密码不能包含中文"));
      } else if (util.validEmpty(value)) {
        return callback(new Error("密码不能包含空格!"));
      } else {
        callback();
      }
    };
    const validChineseAndLetter = (rule, value, callback) => {
      if (util.validChineseAndLetter(value)) {
        return callback(new Error("此处只能输入汉字、字母！"));
      } else {
        callback();
      }
    };
    return {
      util: util,
      tip2: false,
      newPhone: "", // 新手机号
      codeText1: "获取验证码", // 验证旧手机号的验证码
      codeText2: "获取验证码",
      verification1: "", // 验证旧手机号的验证码
      verification2: "",
      phoneVisible: false, // 修改手机号的弹窗
      tip1: false,
      progress: 0, // 修改手机号的进度
      default_head: default_head,
      dialogVisible: false,
      way: "look",
      labelPosition: "left",
      roleKey: "",
      rules: {
        linkName: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { validator: validChineseAndLetter, trigger: "blur" }
        ]
      },
      rulesBox: {
        password: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { validator: checkPassword, trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ]
      },
      modifyPassw: {
        password: "",
        newPassword: ""
      },
      formData: {
        userName: "",
        linkName: "",
        password: "********",
        mobile: "",
        status: true,
        headUrl: "",
        list: [
          {
            roleId: null,
            roleCode: "",
            roleName: ""
          }
        ]
      },
      passw: "",
      pageState: util.getQuery().pageState // 0 编辑状态 不可点取消
    };
  },
  computed: mapState(["userId", "merchantId", "linkName", "headUrl"]),
  created() {
    this.getDetails();
  },
  mounted() {
    if (this.pageState == 0) {
      this.$message({
        message: "请先设置您面向当前商户的姓名",
        type: "warning"
      });
      this.way = "update";
    }
  },
  methods: {
    cutOutNumbers() {
      this.newPhone = util.replaceNumber(this.newPhone);
      if (this.newPhone.substring(0, 1) == 1) {
        this.tip2 = false;
      } else {
        this.tip2 = true;
      }
    },
    cancleChange() {
      this.newPhone = "";
      this.codeText1 = "获取验证码";
      this.codeText2 = "获取验证码";
      this.verification1 = "";
      this.verification2 = "";
      this.phoneVisible = false;
      this.tip1 = false;
      this.tip2 = false;
      this.progress = 0;
    },
    getCode1() {
      if (this.codeText1 != "获取验证码") {
        return false;
      }
      let data = {
        mobile: this.formData.mobile,
        type: 1
      };
      var timer = null;
      var self = this;
      validateCode(data).then(res => {
        if (res.code == 200) {
          self.codeText1 = 60;
          timer = setInterval(res => {
            if (self.codeText1 == 0) {
              clearInterval(timer);
              self.codeText1 = "获取验证码";
            } else {
              self.codeText1 = self.codeText1 - 1;
            }
          }, 1000);
        }
      });
    },
    getCode2() {
      if (this.codeText2 != "获取验证码") {
        return false;
      }
      if (
        this.newPhone == "" ||
        this.newPhone.length != 11 ||
        this.newPhone.substring(0, 1) != 1
      ) {
        this.tip2 = true;
        return false;
      }
      let data = {
        mobile: this.newPhone,
        type: 2
      };
      var timer = null;
      var self = this;
      validateCode(data).then(res => {
        if (res.code == 200) {
          self.codeText2 = 60;
          timer = setInterval(res => {
            if (self.codeText2 == 0) {
              clearInterval(timer);
              self.codeText2 = "获取验证码";
            } else {
              self.codeText2 = self.codeText2 - 1;
            }
          }, 1000);
        }
      });
    },
    checkMoblieCode() {
      if (this.verification1 == "") {
        this.tip1 = true;
        return false;
      }
      let data = {
        mobile: this.formData.mobile,
        code: this.verification1,
        type: 1
      };
      checkMoblieCode(data).then(res => {
        if (res.data.flag == false) {
          this.tip1 = true;
        } else {
          this.tip1 = false;
          this.progress = 1;
        }
      });
    },
    checkMoblieCode2() {
      var self = this;
      if (this.verification2 == "") {
        this.tip1 = true;
        return false;
      }
      let data = {
        old_mobile: this.formData.mobile,
        mobile: this.newPhone,
        code: this.verification2,
        type: 2
      };
      updMobileByCode(data).then(res => {
        if (res.msg == "验证码错误") {
          this.tip1 = true;
        } else {
          if (res.code == 200) {
            this.phoneVisible = false;
            this.tip1 = false;
            this.progress = 0;
            this.$alert("修改成功!", "提示", {
              confirmButtonText: "确定",
              callback: action => {
                let userInfo = JSON.parse(
                  Cookies.get(process.env.COOKIE_NAME + "_userInfo")
                );
                userInfo.mobile = self.newPhone;
                self.$store.commit("SET_MOBILE", userInfo.mobile);
                Cookies.set(
                  process.env.COOKIE_NAME + "_userInfo",
                  JSON.stringify(userInfo)
                );
                window.location.reload();
              }
            });
          }
        }
      });
    },
    handleClose(done) {
      var self = this;
      this.$confirm("确认关闭？")
        .then(_ => {
          self.newPhone = "";
          self.codeText1 = "获取验证码";
          self.codeText2 = "获取验证码";
          self.verification1 = "";
          self.verification2 = "";
          self.phoneVisible = false;
          self.tip1 = false;
          self.progress = 0;
          done();
        })
        .catch(_ => {});
    },
    replaceName(value, obj, key) {
      let res = util.replaceChineseAndLetter(value);
      let result = util.replaceEmpty(res);
      this.$set(obj, key, result);
    },
    getDetails() {
      let that = this;
      let data = {
        merchantId: that.merchantId,
        userId: that.userId
      };
      findUserInfo(data).then(res => {
        let data = res.data;
        if (+res.code == 200) {
          that.formData.linkName = data.linkName;
          that.formData.mobile = data.mobile;
          that.formData.headUrl = data.headUrl;
          that.formData.list = data.roleList;
        } else {
          that.openTips(res.msg, "error");
        }
      });
    },
    saveForm() {
      let that = this;
      this.$refs.formData.validate(valid => {
        if (valid) {
          let data = {
            userId: this.userId,
            merchantId: this.merchantId,
            linkName: this.formData.linkName,
            headUrl: this.formData.headUrl
          };
          updatePersonInfo(data).then(res => {
            if (+res.code == 200) {
              if (that.linkName != data.linkName) {
                that.$store.commit("SET_LINKNAME", data.linkName);
                Cookies.set(
                  process.env.COOKIE_NAME + "_linkName",
                  data.linkName
                );
              }
              if (that.headUrl != data.headUrl) {
                that.$store.commit("SET_HEADURL", data.headUrl);
                let userInfo = JSON.parse(
                  Cookies.get(process.env.COOKIE_NAME + "_userInfo")
                );
                userInfo.headUrl = data.headUrl;
                Cookies.set(
                  process.env.COOKIE_NAME + "_userInfo",
                  JSON.stringify(userInfo)
                );
              }
              if (that.pageState == 0) {
                util.routerReplace("/");
              }
              that.openTips("提交成功！", "success");
              that.getDetails();
              that.way = "look";
            } else {
              that.openTips(res.msg, "error");
            }
          });
          this.$refs.formData.resetFields();
        } else {
          return false;
        }
      });
    },
    cancle() {
      let that = this;
      that.way = "look";
      that.getDetails();
      this.$refs.formData.resetFields();
    },
    //上传图片
    beforeUpload(file) {
      let isJPG =
        file.type === "image/jpg" ||
        file.type === "image/png" ||
        file.type === "image/jpeg";
      let isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像只能为png/jpg/jpeg格式");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    uploadFile1(param) {
      let that = this;
      let fileObj = param.file;
      let data = new FormData();
      data.append("file", fileObj);
      data.append("projectName", fileObj.name);
      uploadFile(data).then(res => {
        if (res.code == 200) {
          that.formData.headUrl = `${getFile}?id=${res.data.id}`;
        } else {
          this.$message({
            message: "图片上传失败",
            type: "error"
          });
        }
      });
    },
    closePasswBox() {
      let that = this;
      that.dialogVisible = false;
      this.$refs.modifyPassw.resetFields();
    },
    submitPassw() {
      var that = this;
      this.$refs.modifyPassw.validate(valid => {
        if (valid) {
          let data = {
            userId: this.userId,
            password: md5(that.modifyPassw.password),
            newPassword: md5(that.modifyPassw.newPassword)
          };
          updatePwd(data).then(res => {
            if (res.code == 200) {
              this.$alert("密码修改成功,请重新登录", "提示", {
                confirmButtonText: "确定",
                callback: () => {
                  Cookies.remove(process.env.COOKIE_NAME + "_companyName");
                  Cookies.remove(process.env.COOKIE_NAME + "_isFirstLogin");
                  Cookies.remove(process.env.COOKIE_NAME + "_isShop");
                  Cookies.remove(process.env.COOKIE_NAME + "_linkName");
                  Cookies.remove(process.env.COOKIE_NAME + "_merchantId");
                  Cookies.remove(process.env.COOKIE_NAME + "_token");
                  Cookies.remove(process.env.COOKIE_NAME + "_userInfo");
                  Cookies.remove(process.env.COOKIE_NAME + "_soUrce");
                  Cookies.remove(process.env.COOKIE_NAME + "_isOwnAuth");
                  Cookies.remove(process.env.COOKIE_NAME + "_businessScope");
                  location.reload();
                }
              });
            } else {
              that.openTips(res.msg, "error");
            }
          });
        } else {
          return false;
        }
      });
    },
    openTips(tip, type) {
      this.$message({
        message: tip,
        type: type
      });
    }
  }
};
</script>
<style lang='less'>
.personalCenter {
  .line {
    .input {
      input {
        height: 100%;
      }
    }
  }
  .avatar-uploader {
    text-align: left;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: auto;
    height: 100px;
    display: block;
  }
}
</style>
<style lang='less' scoped>
[v-cloak] {
  display: none !important;
}
.personalCenter {
  margin-left: -11px;
  height: 100%;
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  overflow: hidden;
  .changePhoneBox {
    .tip {
      margin-left: 100px;
      color: red;
      font-size: 12px;
    }
    .height {
      margin-bottom: 20px;
    }
    .line {
      display: flex;
      .title {
        width: 100px;
        line-height: 30px;
      }
      .phone {
        line-height: 30px;
      }
      .input {
        height: 30px;
        width: initial;
      }
      .getCode {
        width: 100px;
        margin-left: 20px;
      }
    }
  }
  .newPhone {
    .tip {
      margin-left: 100px;
      color: red;
      font-size: 12px;
    }
    .height {
      margin-bottom: 20px;
    }
    .line {
      display: flex;
      .title {
        width: 100px;
        line-height: 30px;
      }
      .phone {
        line-height: 30px;
      }
      .input {
        height: 30px;
        width: initial;
      }
      .getCode {
        width: 100px;
        margin-left: 20px;
      }
    }
  }
  .personal-side {
    border-right: 1px solid #e6e6e6;
    padding-top: 15px;
    background: #fff;
    width: 209px;
    height: 100%;
    span {
      background: #dbf0fd;
      color: #2da3ea;
      height: 56px;
      line-height: 56px;
      display: block;
      font-size: 14px;
      text-indent: 20px;
    }
  }
  .personal-main {
    flex: 1;
    height: 100%;
    width: 100%;
    position: relative;
    .personal-main-wrap {
      position: absolute;
      top: 11px;
      left: 11px;
      right: 11px;
      bottom: 10px;
      overflow: auto;
      background: #fff;
      padding: 20px 11px 11px 40px;
      .el-form {
        width: 500px;
        .el-form-item {
          margin-bottom: 5px;
          padding: 6px 0;
        }
      }
      p {
        text-align: left !important;
      }
      .personal-password {
        padding-right: 30px;
      }
      .headeImg {
        width: auto;
        height: 100px;
        display: block;
        float: left;
      }
      .personal-btn {
        padding-top: 30px;
        padding-bottom: 20px;
        text-align: left;
      }
    }
  }
}
</style>
